package main

import (
	"github.com/ngaut/log"
	"global/structs"
	"server/ote/model"
	"sync"
)

type Data struct {
	mu sync.Mutex
	CoinPair map[string]structs.CoinPair
	NoFee 	 map[int]bool
}

func NewData() *Data {
	data := &Data{
		CoinPair: make(map[string]structs.CoinPair),
		NoFee: 	  make(map[int]bool),
	}
	return data
}

func (d *Data) LoadData() {
	d.GetCoinPair()
	d.GetNoFeeUsers()
}

// 添加交易对
func (d *Data) AddCoinPiar(pair structs.CoinPair) error {
	if _, ok := d.CoinPair[pair.Name]; !ok {
		d.mu.Lock()
		d.CoinPair[pair.Name] = pair
		d.mu.Unlock()
	}
	return nil
}

func (d *Data) GetNoFeeUsers() {
	ids, err := model.UserModel.GetNoFeeUIds()
	if err != nil {
		log.Fatalf("get no fee users error, msg: %s", err.Error())
		return
	}
	for _, id := range ids {
		d.NoFee[id] = true
	}

	// 如果没有包含官方用户，手动添加
	if _, ok := d.NoFee[OFFICIAL_UID]; !ok {
		d.NoFee[OFFICIAL_UID] = true
	}

	log.Infof("load no fee user success, length: %d, user: %d", len(d.NoFee), ids)
}

func (d *Data) GetCoinPair() {
	pairs, err := model.CoinPairModel.GetAll()
	log.Infof("pais: %v", pairs)
	if err != nil {
		log.Fatalf("init coin pair data error, msg: %s", err.Error())
	}

	for _, pair := range pairs {
		d.mu.Lock()
		d.CoinPair[pair.Name] = pair
		d.mu.Unlock()
	}
	log.Infof("load coin pair success, length: %d", len(d.CoinPair))
}

func (d *Data) RemoveNoFeeUser(uid int) {
	if _, ok := d.NoFee[uid]; ok {
		d.mu.Lock()
		delete(d.NoFee, uid)
		d.mu.Unlock()
	}
}

func (d *Data) AddNoFeeUser(uid int) {
	if _, ok := d.NoFee[uid]; !ok {
		d.mu.Lock()
		d.NoFee[uid] = true
		d.mu.Unlock()
	}
}

func (d *Data) GetOne(coinPair string) (bool, structs.CoinPair) {
	if item, ok := d.CoinPair[coinPair]; ok {
		return true, item
	}
	return false, structs.CoinPair{}
}